//
//  aquireData.m
/*
 Copyright 2009 Jack Whitsitt
 Conact: sintixerr@gmail.com | http://sintixerr.wordpress.com
 
 This file is part of "pkviz".
 
 "pkviz" is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 "pkviz" is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with "pkviz".  If not, see <http://www.gnu.org/licenses/>.
 */ 

#import "aquireData.h"


@implementation aquireData

/*
- (IBAction)clearStore:(id)sender
{
//- (NSPersistentStoreCoordinator *) persistentStoreCoordinator	
//	mycontext = [[NSApp delegate] managedObjectContext];	

	NSPersistentStoreCoordinator *store_coordinator = [[NSApp delegate] persistentStoreCoordinator];
	NSLog(@"uhm count: %i", [[store_coordinator persistentStores] count]);
}
*/

- (IBAction)loadData_click:(id)sender 
{	
	int i; // Loop counter.
	
	// Create the File Open Dialog class.
	NSOpenPanel* openDlg = [NSOpenPanel openPanel];
	
	// Enable the selection of files in the dialog.
	[openDlg setCanChooseFiles:YES];
	
	// Enable the selection of directories in the dialog.
	[openDlg setCanChooseDirectories:YES];
	
	// Display the dialog.  If the OK button was pressed,
	// process the files.
	if ( [openDlg runModalForDirectory:nil file:nil] == NSOKButton )
	{
		// Get an array containing the full filenames of all
		// files and directories selected.
		NSArray* files = [openDlg filenames];
		
		// Loop through all the files and process them.
		for( i = 0; i < [files count]; i++ )
		{
			NSString* fileName = [files objectAtIndex:i];
			NSLog(@"file is: %@", fileName);
			NSLog(@"Start Reading");
			[self readCSV:fileName];
			NSLog(@"Done Reading");
			// Do something with the filename.
		}
	}
}



- (NSArray *)chk_pk_exist:(double)pkc
{	
	NSArray *dummy = nil;
	return dummy;
}



- (NSManagedObject *)genByte:(NSString *)bval atpos:(float)pkp
{
		// **** CONVERT STRING-HEX BYTE VALUE TO INT
	NSNumber *bval_num;
	
	NSScanner *scanner;
	int tempInt;
	
	NSString *hexVal = [@"0x" stringByAppendingString:bval];

	scanner = [NSScanner scannerWithString:hexVal];
	[scanner scanHexInt:&tempInt];
	bval_num = [NSNumber numberWithInt:tempInt];
	
	int bval_int = [bval_num intValue];
	
	// **** CREATE THE BYTE

	NSManagedObject *byte = [NSEntityDescription insertNewObjectForEntityForName:@"pkByte" inManagedObjectContext:mycontext];

	if ([[existing_val objectAtIndex:bval_int] objectAtIndex:pkp] == [NSNumber numberWithInt:0]) // if byte not in array, not in context yet
	{

		[byte setValue:bval forKey:@"byteValue"];
		[byte setValue:[NSNumber numberWithInteger:pkp] forKey:@"position"];
		 		
		[[existing_val objectAtIndex:bval_int] replaceObjectAtIndex:pkp withObject:[byte objectID]]; // add byte obj id to array
	}
	
	else 
	{ byte = [mycontext objectWithID:[[existing_val objectAtIndex:bval_int] objectAtIndex:pkp]];}

	return byte;	
}



- (void)readCSV:(NSString *)dataFile
{
	//*************** SET UP BYTE-POSITION-EXIST-CHECK-ARRAY
	
	int maxbval = 256;
	int maxposval = 3000;
	existing_val = [NSMutableArray arrayWithCapacity:maxbval];
	int setarray = 0;
	
	while (setarray < maxbval) {
		
		NSMutableArray *temp3k = [NSMutableArray arrayWithCapacity:maxposval];
		
		int addzeros=0;
		
		while (addzeros < maxposval )
		{
			[temp3k addObject:[NSNumber numberWithInt:0]];
			++addzeros;
		}
			   
		[existing_val insertObject:temp3k atIndex:setarray];
		
		++setarray;
	}
	// **** SET UP CORE DATA CONTEXT AND BYTE CHECK PREDICATE ****
	
	mycontext = [[NSApp delegate] managedObjectContext];
	NSManagedObject *packet = nil; // new data entity
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	
	[request setEntity:[NSEntityDescription entityForName:@"pkByte" inManagedObjectContext:mycontext]];

	//***************READ IN AND PARSE FILE

	NSString *tmp;
    NSArray *lines;
	lines = [[NSString stringWithContentsOfFile:dataFile] componentsSeparatedByString:@"\n"];
//    lines = [[NSString stringWithContentsOfFile:@"/rawpcap2.txt"] componentsSeparatedByString:@"\n"];
			  	
    NSEnumerator *nse = [lines objectEnumerator];
	
	int first_packet = 0;
	int packet_id = 0;
	int pos = 0;
	
	NSString *byteval;
	NSMutableSet *byteSet;
	
//    while((tmp = [nse nextObject]) && (packet_id < 500)) 
	while(tmp = [nse nextObject]) 
	{
		// Step 1: get lines that start with 0x ***************
		NSCharacterSet *cset = [NSCharacterSet whitespaceAndNewlineCharacterSet];
		NSString *s1_tmp = [tmp stringByTrimmingCharactersInSet: cset];
		NSScanner *step1 = [NSScanner scannerWithString:s1_tmp];

		if ([step1 scanString:@"0x" intoString:nil] == YES) {
			NSString *s2_tmp = s1_tmp;
			NSString *ohex = @"0x0000";
			NSStringCompareOptions compareopts = NSCaseInsensitiveSearch;

			// Step 2: See if we're the first line in the packet **************
			if ([s2_tmp compare:ohex options:compareopts range:(NSMakeRange(0,6))] == NO) {
				
				if (first_packet != 0) { packet_id++; }
				
				else { first_packet=1; }
				
				pos = 0;

				if (1) // we really should be checking to see if packet exists, like we do for byte, but we wont yet
				{
					packet = [NSEntityDescription insertNewObjectForEntityForName:@"packet" inManagedObjectContext:mycontext];
					[packet setValue:[NSNumber numberWithInteger:packet_id] forKey:@"packetNum"];
				}
			}
			
			// Step 3: Remove 0x's and then remove Ascii display of data **************
			NSString *s3_tmp_a = [s2_tmp substringFromIndex:9]; // no more 0x's
			NSArray *s3_tmp_b = [s3_tmp_a componentsSeparatedByString:@"  "]; // split to data/ascii
			NSString *s3_tmp_c = [s3_tmp_b objectAtIndex:0]; // got data from array
			NSString *s3_tmp_d = [s3_tmp_c stringByReplacingOccurrencesOfString:@" " withString:@""]; //removing spaces between byte pairs
			
			// Step 4: Split lines into packets: id,val,position,packetnum and add to Core Data ****************
//			int pos = 0;
			float pakpos = 0;
			
			for (int pos_step = 0; pos_step < ([s3_tmp_d length]/2); pos_step++) 
			{
				byteSet = nil;
				byteval = [s3_tmp_d substringWithRange:(NSMakeRange(pos_step*2,2))]; 
				pakpos = pos/2;
				
				byteSet = [packet mutableSetValueForKey:@"bytes"];
				
				[byteSet addObject:[self genByte:byteval atpos:pakpos]]; //setByte and add new byte to packet
				
				pos+=2;
			}
		}
	}
	
	NSLog(@"BING!!!!!");
}

@end